from django.shortcuts import render_to_response
from django.views.decorators.http import require_POST
from django.http import HttpResponse
from goearconsumer import GoearConsumer
from playlists import Playlist
import simplejson

PAGES_TO_REQUIRE = 5

def index(req):

	return render_to_response('playlists/index.html')


@require_POST
def search_song(req):
	
	
	first_call = req.POST.get('firstCall') == '1'

	if first_call is True:
		
		page = 0
		
		query = req.POST.get('song')
				
		consumer = GoearConsumer()
	
		meta_data_list = []
		
		for p in range(PAGES_TO_REQUIRE-1):
			meta_data_list.append(consumer.search_songs(query, p))
			
	else:
		page = req.session.get('page')
		meta_data_list = req.session.get('search_result')
		
		if len(meta_data_list) == page:
			return HttpResponse(HttpResponse(simplejson.dumps({'result':'NOMORESONGS'}), 
						    mimetype='application/json'))
	ans = []
	
	if meta_data_list[0] <> []:
		
		for m in meta_data_list[page]:
			ans.append({'name':m.get_name(), 'artist':m.get_artist(), 
				   'location': m.get_mp3_url()})
			
		req.session['search_result'] = meta_data_list
		req.session['page'] = page+1
	else:
		print 'no results'
		ans = {'result':'NORESULTS'}
		
	return HttpResponse(HttpResponse(simplejson.dumps(ans), 
						    mimetype='application/json'))
	

@require_POST
def clear_playlist(req):
	
	ans = {'result':'OK'}
	
	try:
		p = req.session['playlist']
		p.delete()
		del req.session['playlist']
	except KeyError:
		ans = {'result':'NOPLAYLIST'}
	
	return HttpResponse(simplejson.dumps(ans), 
						    mimetype='application/json')
	
@require_POST
def create_playlist(req):
	
	songs = req.POST.get('songs')
		
	if songs == "":
		print 'nada para hacer'
		return HttpResponse(simplejson.dumps({'result':'NOSONGS'}), 
						    mimetype='application/json')
		
	try:
		playlist = req.session['playlist']
	except KeyError:
		playlist = Playlist()
	
	playlist.addSongs(songs)
		
	req.session['playlist'] = playlist
	
	return HttpResponse(simplejson.dumps({ 'url': playlist.get_url() }), 
									    mimetype='application/json')
		
	